import 'dart:async';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

import '../config/const_config.dart';

class LocationPage extends StatefulWidget {
  const LocationPage({super.key});

  @override
  State<LocationPage> createState() => _LocationPageState();
}

class _LocationPageState extends State<LocationPage> {
  // location data
  var locationMessage = '';

  void getCurLocation() async {
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    var lastPosition = await Geolocator.getLastKnownPosition();
    // print('position: $position, lastPosition: $lastPosition');
    setState(() {
      locationMessage = "$position.latitude, $position.longtitude";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("定位"),
      ),
      body: Center(
        child: Row(children: [Text(locationMessage)]),
      ),
    );
  }
}

class GaoDeLocationPage extends StatefulWidget {
  const GaoDeLocationPage({super.key});

  @override
  State<GaoDeLocationPage> createState() => _GaoDeLocationPageState();
}

class _GaoDeLocationPageState extends State<GaoDeLocationPage> {
  // location data
  var locationMessage = '';

  final _locationPlugin = AMapFlutterLocation();
  // 监听定位
  late StreamSubscription<Map<String, Object>> _locationListener;
  String _latitude = ""; //纬度
  String _longitude = ""; //经度
  String country = ""; // 国家
  String province = ""; // 省份
  String city = ""; // 市
  String district = ""; // 区
  String street = ""; // 街道
  String adCode = ""; // 邮编
  String address = ""; // 详细地址
  String cityCode = ""; //区号

  Future<void> reqPermission() async {
    var permission = await reqLocationPermission();
    if (permission ) {
      print("通过");
    } else {
      print("未通过");
    }
  }
  // 申请定位请求
  Future<bool> reqLocationPermission() async {
    var status = await Permission.location.status;
    if (PermissionStatus.granted == status) {
      return true;
    }
    PermissionStatus permissionStatus = await Permission.location
        .onGrantedCallback(() => true)
    .request();

    if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
      // Use location.
      print("location");
      
    }
     // = await Permission.location.request();
    if (permissionStatus.isGranted) {
      return true;
    }
    if (permissionStatus.isPermanentlyDenied) {
      // The user opted to never again see the permission request dialog for this
      // app. The only way to change the permission's status now is to let the
      // user manually enables it in the system settings.
      openAppSettings();
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("高德定位"),
      ),
      body: Center(
        child: Column(children: [Text("经度:$_longitude"),
          Text("纬度:$_latitude"),
          Text('国家：$country'),
          Text('省份：$province'),
          Text('城市：$city'),
          Text('区：$district'),
          Text('城市编码：$cityCode'),
          Text('街道：$street'),
          Text('邮编：$adCode'),
          Text('详细地址：$address'),
          const SizedBox(height: 20),
          ElevatedButton(
            child: const Text('开始定位'),
            onPressed: () {
              _startLocation();
            },
          ),
          ElevatedButton(
            child: const Text('停止定位'),
            onPressed: () {
              _stopLocation();
            },
          ),]),
      ),
    );
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    reqPermission();
    // 设置key
    AMapFlutterLocation.setApiKey(ConstConfig.androidKey, ConstConfig.iosKey);
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    reqSystemLocationType();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      print("############");
      print(result);
      setState(() {
        _latitude = result["latitude"].toString();
        _longitude = result["longitude"].toString();
        country = result['country'].toString();
        province = result['province'].toString();
        city = result['city'].toString();
        district = result['district'].toString();
        street = result['street'].toString();
        adCode = result['adCode'].toString();
        address = result['address'].toString();
        cityCode = result['cityCode'].toString();
      });
    });
  }

  Future<void> reqSystemLocationType() async{
    AMapAccuracyAuthorization authorization = await _locationPlugin.getSystemAccuracyAuthorization();
    if (authorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型1");
    } else if (authorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("other定位类型");
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      ///开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = false;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }
}
